<?php

/**
 * Spectrum class
 *
 * @package default
 * @author Giv Parvaneh giv@givp.org
 **/
class Spectrum {
	
	private $src;
	private $palette = array();
	private $img;
	private $img2;
	private $wid = 50; // default number of colors to return
	
	public function setImage($src){
		
		$this->src = $src;
		$this->setSourceFile();
	}
	
	public function getSourceFile(){
		
		$this->setSourceFile();
		return($this->img);
	}
	
	
	public function processImage(){
		
		$finalpalette = $this->getAllColors();
		$this->destroyImage();
		
		return $finalpalette;
		
	}
	
	
	private function setSourceFile(){

		$this->img = @ImageCreateFromJpeg($this->src) OR DIE ('Invalid image source');
		
		// convert from true color to palette + dithering
		imagetruecolortopalette($this->img, true, 50);
	}
	
	
	private function getAllColors(){
		
		$totalColors = ImageColorsTotal($this->img);
		
		for($n=0; $n<$totalColors; ++$n)
		  {
		    
		    $color = $this->getColor($this->img, $n);
			
		    // omit white
		    if($color["red"] != 255 && $color["green"] != 255 && $color["blue"] != 255)
		    {
		    	$this->palette[] = $color;
		    }
		  }
		
		return $this->palette;
	}
	
	public function getColor($image, $index){
	    
	    $c = ImageColorsForIndex($image, $index);
	    
		$hex = $this->rgb2hex($c['red'],$c['green'],$c['blue']);
	
		$color = array("red"=>$c['red'],"green"=>$c['green'],"blue"=>$c['blue'],"hex"=>$hex);
		return $color;
	}
	
	/**
	 * RGB 2 HEX function
	 *
	 * @return hex string
	 **/
	private function rgb2hex($r, $g=-1, $b=-1)
	{
    if (is_array($r) && sizeof($r) == 3)
        list($r, $g, $b) = $r;

    $r = intval($r); $g = intval($g);
    $b = intval($b);

    $r = dechex($r<0?0:($r>255?255:$r));
    $g = dechex($g<0?0:($g>255?255:$g));
    $b = dechex($b<0?0:($b>255?255:$b));

    $color = (strlen($r) < 2?'0':'').$r;
    $color .= (strlen($g) < 2?'0':'').$g;
    $color .= (strlen($b) < 2?'0':'').$b;
    return $color;
	}
	
	
	private function destroyImage(){
		ImageDestroy($this->img);
	}
	
	
}

?>